package il.ac.tau.dbcourse.db;

import il.ac.tau.dbcourse.db.annotations.SQLTable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@SQLTable(table = "ARTIST")
public class Artist extends AbsPersistence {
	private String name = "";

	public Artist() {
		tableName = PersistenceManager.getTableName(this.getClass());
		setDirty(true);
	}

	public Artist(Connection conn, Long id) {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			tableName = PersistenceManager.getTableName(this.getClass());
			stmt = conn.prepareStatement("select * from " + tableName
					+ " where ID=?");
			stmt.setLong(1, id);

			rs = stmt.executeQuery();
			if (!rs.next())
				throw new SQLException();
			name = rs.getString("name");
			this.id = id;
			setDirty(false);
			rs.close();
			stmt.close();
			rs = null;
			stmt = null;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (rs != null)
					rs.close();
			} catch (Exception e) {
			}

		}
	}

	@Override
	protected Long saveImpl(Connection conn) {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {

			if (id == null) {
				stmt = conn.prepareStatement("insert into " + tableName
						+ " (NAME) " + "values (?)",
						Statement.RETURN_GENERATED_KEYS);
			} else {
				stmt = conn.prepareStatement("update " + tableName + " set "
						+ "NAME=? " + "where ID=?");
			}

			stmt.setString(1, name);

			if (id != null)
				stmt.setLong(2, getId());

			stmt.executeUpdate();
			if (id == null) {
				rs = stmt.getGeneratedKeys();
				if (rs.next()) {
					String rowId = rs.getString(1);
					id = PersistenceManager.getId(conn, this.getClass(), rowId);
				}
				rs.close();
				rs = null;
			}

			stmt.close();
			stmt = null;
			setDirty(false);
			return id;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (rs != null)
					rs.close();
			} catch (Exception e) {
			}

		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		if (this.name.compareTo(name) != 0)
			setDirty(true);
		this.name = name;
	}

}
